package com.mjk.manager.amis.core.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.util.TreeUtils;
import com.mjk.manager.amis.core.dto.SessionDetails;
import com.mjk.manager.amis.core.model.PlatSys;
import com.mjk.manager.amis.core.model.PlatUser;
import com.mjk.manager.amis.core.model.SysMenu;
import com.mjk.manager.amis.core.model.SysPage;
import com.mjk.manager.amis.core.utils.SessionHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/mamis")
@Slf4j
public class AmisMainController {
    @Autowired
    private BeeDBService beeDBService;
    @Autowired
    private SessionHolder sessionHolder;

    //    @GetMapping(value = {"", "/"})
//    public String home(HttpServletRequest request, HttpServletResponse response, Model model) {
//        SessionDetails session = sessionHolder.getSession(request);
//        if(null == session){
//            return  "forward:/index1.html"; // 重定向到 index.html
//        }
//        try {
//            String sysId = sessionHolder.getSystem(request).getId();
//            String sysCode = PlatSys.PLATFORM_CODE;
//            BeeQueryWrapper wrapper = new BeeQueryWrapper(PlatSys.class);
//            wrapper.eq(PlatSys::getId, sysId);
//            PlatSys sys = (PlatSys) beeDBService.findOneByWrapper(wrapper);
//            sysCode = sys.getCODE();
//            model.addAttribute("sysCode", sys.getCODE());
//            model.addAttribute("appName", sys.getNAME());
//            model.addAttribute("appLogo", sys.getLOGO());
//            model.addAttribute("appHeader", sys.getHEADER());
//            model.addAttribute("appFooter", sys.getFOOTER());
//            model.addAttribute("appFavicon", sys.getFAVICON());
//        } catch (Exception e) {
//            try {
//                response.sendRedirect("/login");
//            } catch (IOException e1) {
//                log.error(e1.getLocalizedMessage(), e1);
//            }
//        }
//        PlatUser user = session.getCurUser();
//        if (null != user) {
//            model.addAttribute("username", user.getNAME());
//            model.addAttribute("loginName", user.getLOGIN_NAME());
//        } else {
//            model.addAttribute("username", "admin");
//            model.addAttribute("loginName", "admin");
//        }
//        model.addAttribute("contextPath", request.getContextPath());
//        return "app";
//    }
    @GetMapping("/preview/{pageId}")
    public String page(HttpServletRequest request, @RequestParam("sysCode") String sysCode,
                       @PathVariable("pageId") String pageId, Model model) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatSys());
        wrapper.eq(PlatSys::getId, sessionHolder.getSystem(request).getId());
        List<PlatSys> sys = beeDBService.findManyByWrapper(wrapper);

        model.addAttribute("sysCode", sys.get(0).getCODE());
        BeeQueryWrapper wrapper1 = new BeeQueryWrapper(new SysPage());
        wrapper1.eq(SysPage::getId, pageId);
        SysPage page = (SysPage) beeDBService.findOneByWrapper(wrapper1);
        //model.addAttribute("js", "/mamis/pages/" + pageId + ".js?_t=" + new Date().getTime() + "&sysCode=" + sysCode);
        model.addAttribute("json", page.getCONTENT());
        model.addAttribute("contextPath", request.getContextPath());

        return "page";
    }
    @GetMapping("/editor/{pageId}")
    public String editor(HttpServletRequest request, @RequestParam("sysCode") String sysCode,
                         @PathVariable("pageId") String pageId, Model model) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatSys());
        wrapper.eq(PlatSys::getId, sessionHolder.getSystem(request).getId());
        List<PlatSys> sys = beeDBService.findManyByWrapper(wrapper);
        long time = new Date().getTime();

        model.addAttribute("sysCode", sys.get(0).getCODE());
        BeeQueryWrapper wrapper1 = new BeeQueryWrapper(new SysPage());
        wrapper1.eq(SysPage::getId, pageId);
        SysPage page = (SysPage) beeDBService.findOneByWrapper(wrapper1);
        model.addAttribute("json", page.getCONTENT());
//        model.addAttribute("js", "/mamis/pages/" + pageId + ".js?_t=" + time + "&sysCode=" + sysCode);
        model.addAttribute("pageId", pageId);

        model.addAttribute("contextPath", request.getContextPath());

        return "editor";
    }

    @GetMapping("/pages/{pageId}.js")
    @ResponseBody
    public String pageJS(HttpServletRequest request, @RequestParam("sysCode") String sysCode,
                         @PathVariable("pageId") String pageId, @RequestParam Map<String, Object> data) {
        // 从当前组织下获取页面
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new SysPage());
        wrapper.eq(SysPage::getId, pageId);

        SysPage page = (SysPage) beeDBService.findOneByWrapper(wrapper);
        String content = page.getCONTENT();
        JSONObject json = JSONUtil.parseObj(content);

        // 使用查询参数数据覆盖 json 中配置的数据
//		if (json.containsKey("data")) {
//			JSONObject oldData = json.getJSONObject("data");
//			oldData.putAll(data);
//			json.set("data", oldData);
//		} else {
//			json.set("data", data);
//		}

        // 返回 js 文件内容
        return "window.amisJSON = " + JSONUtil.toJsonPrettyStr(json);
    }

    @GetMapping("/pages/site.json")
    @ResponseBody
    public BeeResponse siteJSON(HttpServletRequest request) {
        SessionDetails session = sessionHolder.getSession(request);

        BeeQueryWrapper wrapper = new BeeQueryWrapper(new SysMenu());
        wrapper.condition("OWN_SYS_ID=#{1} or OWN_SYS_ID='' or OWN_SYS_ID='' ", sessionHolder.getSystem(request).getId());
        wrapper.orderBy(" SEQ  ");
        // 查询菜单列表
        List<SysMenu> menus = beeDBService.findManyByWrapper(wrapper);
        List<SysMenu> menuTree = TreeUtils.list2Tree(menus, "0", "id", "PID", "children", false);
        // 构造页面列表

        List<Map<String, Object>> pageList = buildPageList(menuTree, session.getCurSys().getHOME(), request.getContextPath(),
                session.getCurSys().getCODE(), new Date().getTime());

        // 返回 site.json
        Map<String, Object> ret = new HashMap<>();
        ret.put("pages", pageList);

        return BeeError.BEE_SUC.tranceError(ret);
    }

    @GetMapping("/pages/{pageId}.json")
    @ResponseBody
    public String pageJSON(HttpServletRequest request, @RequestParam("sysCode") String sysCode,
                           @PathVariable("pageId") String pageId) {

        // 从当前组织下获取页面
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new SysPage());
        wrapper.eq(SysPage::getId, pageId);

        SysPage page = (SysPage) beeDBService.findOneByWrapper(wrapper);
        return page.getCONTENT();
    }

    @GetMapping("/page/json")
    @ResponseBody
    public String pagejson(HttpServletRequest request, String pageId) {
        String json = """
                {
                    "type": "page",
                    "body": {
                      "type": "iframe",
                      "src": "%s"
                    }
                }
                """;
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new SysMenu());
        wrapper.eq(SysMenu::getId, pageId);
        SysMenu menu = (SysMenu) beeDBService.findOneByWrapper(wrapper);
        if (ObjectUtils.isEmpty(menu.getURL())) {
            return String.format(json, menu.getPAGE_ID());
        } else {
            return String.format(json, menu.getURL());
        }
    }

    private List<Map<String, Object>> buildPageList(List<SysMenu> menuList, String homeUrl, String contextPath,
                                                    String sysCode, long time) {
        List<Map<String, Object>> pages = new ArrayList<>();

        // 菜单页面组
        Map<String, Object> menuPage = new HashMap<>();
        pages.add(menuPage);

        // 菜单列表
        List<Map<String, Object>> menus = new ArrayList<>();
        menuPage.put("children", menus);

        // 添加菜单项
        for (SysMenu item : menuList) {
            menus.add(buildMenuItem(item, contextPath, sysCode, time));
        }

        Map<String, Object> homePage = new HashMap<>();
        pages.add(homePage);

        homePage.put("label", "/"); // 有 / 后缀跳转
        homePage.put("url", contextPath + "/" + sysCode + "/");
        homePage.put("redirect", contextPath + "/" + sysCode);

        homePage = new HashMap<>();
        pages.add(homePage);

        homePage.put("label", ""); // 无 / 后缀跳转
        homePage.put("url", contextPath + "/" + sysCode);

        // 指定登录后跳转页面
        if (StrUtil.isBlank(homeUrl) || "/".equals(homeUrl)) {
            // 未设置或无效设置
            if (menus.size() == 0) {
                // 没有菜单访问权限，直接返回
                return pages;
            }
            homePage.put("redirect", (String) menus.get(0).get("url"));
        } else if (homeUrl.startsWith("/")) {
            // 绝对路径
            homePage.put("redirect", contextPath + "/" + sysCode + homeUrl);
        } else {
            // 相对路径，一般不存在这种设置
            homePage.put("redirect", homeUrl); // 首页 url
        }

        return pages;
    }

    private Map<String, Object> buildMenuItem(SysMenu item, String contextPath, String sysCode, long time) {
        Map<String, Object> page = new HashMap<>();

        page.put("label", item.getNAME());
        page.put("icon", item.getICON());
        if (StrUtil.isNotBlank(item.getURL()) && item.getURL().startsWith("/")) {
            page.put("url", contextPath + "/" + sysCode + item.getURL());
        } else {
            page.put("url", item.getURL());
        }

        List<Map<String, Object>> children = new ArrayList<Map<String, Object>>();
        if (item.getChildren() != null) {
            for (SysMenu subItem : item.getChildren()) {
                children.add(buildMenuItem(subItem, contextPath, sysCode, time));
            }

            if (StrUtil.equals("/dev", item.getURL())) {
                Map<String, Object> editor = new HashMap<>();

                editor.put("label", "页面编辑器");
                editor.put("url", contextPath + "/" + sysCode + "/dev/editor");
                editor.put("visible", false);
                editor.put("schemaApi", "/amis/pages/dev-editor.json?_t=" + time + "&sysCode=" + sysCode);

                children.add(editor);
            }
        }

        if (children.size() > 0) {
            page.put("children", children);
            page.put("redirect", children.get(0).get("url"));
        } else {
            if (SysMenu.TYPE_DYNAMIC_PAGE == item.getTYPE()) {
                page.put("schemaApi", "/mamis/pages/" + item.getPAGE_ID() + ".json?_t=" + time + "&sysCode=" + sysCode);
            } else {
                if (ObjectUtils.isEmpty(item.getPAGE_ID())) {
                    page.put("schemaApi", "/mamis/page/json?pageId=" + item.getId());
                } else {
                    page.put("schemaApi", "/amis/pages/" + item.getPAGE_ID() + ".json?_t=" + time + "&sysCode=" + sysCode);
                }
            }
        }

        return page;
    }
}
